#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>

#include "../Log.hpp"

static const int backlog = 10;

class Socket
{
private:
    int _sockfd; // 通信套接字描述符

public:
    Socket() : _sockfd(-1) {}
    Socket(int fd) : _sockfd(fd) {}
    ~Socket() { Close(); }
    // 获取文件描述符
    int Fd() { return _sockfd; }
    // 关闭文件描述符
    void Close()
    {
        if (_sockfd != -1)
        {
            close(_sockfd);
            _sockfd = -1;
        }
    }

    // 创建套接字
    bool CreateSocket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd == -1)
        {
            ERR_LOG("create socket fail");
            return false;
        }
        INF_LOG("create listen socket success, fd:%d", _sockfd);
        return true;
    }
    // 绑定ip和端口号
    bool Bind(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(addr);

        int ret = bind(_sockfd, (const sockaddr *)&addr, len);
        if (ret == -1)
        {
            ERR_LOG("bind ip and port fail");
            return false;
        }
        INF_LOG("bind ip and port success");
        return true;
    }
    // 服务端开始监听
    bool Listen()
    {
        int ret = listen(_sockfd, backlog);
        if (ret == -1)
        {
            ERR_LOG("server listen sockfd fail");
            return false;
        }
        INF_LOG("server listen...");
        return true;
    }
    // 客户端向服务端建立连接
    bool Connect(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(addr);

        int ret = connect(_sockfd, (const sockaddr *)&addr, len);
        if (ret == -1)
        {
            ERR_LOG("client connect server fail");
            return false;
        }
        INF_LOG("client connect server success");
        return true;
    }
    // 服务端获取新连接生成套接字
    int Accept()
    {
        int newfd = accept(_sockfd, nullptr, nullptr);
        if (newfd == -1)
        {
            ERR_LOG("server accept fail");
            return -1;
        }
        INF_LOG("-------------get a new link-------------");
        return newfd;
    }

    // 发送数据
    ssize_t Send(const void *buf, size_t len, int flag = 0)
    {
        ssize_t ret = send(_sockfd, buf, len, flag);
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
                return 0;
            ERR_LOG("socket send fail");
            return -1;
        }
        return true;
    }
    ssize_t SendNonBlock(const void *buf, size_t len)
    {
        return Send(buf, len, MSG_DONTWAIT);
    }
    // 接收数据
    ssize_t Recv(void *buf, size_t len, int flag = 0)
    {
        ssize_t ret = recv(_sockfd, buf, len, flag);
        if (ret <= 0)
        {
            if (errno == EAGAIN || errno == EINTR)
                return 0;
            ERR_LOG("socket recv fail");
            return -1;
        }
        return ret;
    }
    ssize_t RecvNonBlock(void *buf, size_t len)
    {
        return Recv(buf, len, MSG_DONTWAIT);
    }

    // 创建一个服务端连接
    bool CreateServer(uint16_t port, const std::string &ip = "127.0.0.1", bool block_flag = false)
    {
        // 1. 创建套接字，2. 设置套接字为非阻塞，3. 绑定地址端口，4. 开始监听 5. 开启地址端口重用
        if (CreateSocket() == false)
            return false;
        if (block_flag)
            NonBlock(); // 设置文件描述符为非阻塞
        if (Bind(ip, port) == false)
            return false;
        if (Listen() == false)
            return false;
        ReuseAddressPort(); // 启动地址端口重用
        return true;
    }
    // 创建一个客户端连接
    bool CreateClient(uint16_t port, const std::string &ip)
    {
        // 1. 创建套接字 2.向服务端发起连接
        if (CreateSocket() == false)
            return false;
        if (Connect(ip, port) == false)
            return false;
        return true;
    }

    // 设置地址断端口重用
    void ReuseAddressPort()
    {
        int val = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, (void *)&val, sizeof(val));
    }
    // 设置文件描述符为非阻塞
    void NonBlock()
    {
        // 获取文件描述符的属性
        int flag = fcntl(_sockfd, F_GETFL, 0);
        // 添加文件描述符的属性
        fcntl(_sockfd, F_SETFL, flag | O_NONBLOCK);
    }
};